import serial
import serial.tools.list_ports
import threading


def list_serial_ports():
    """列出所有可用的串口"""
    ports = serial.tools.list_ports.comports()
    return [port.device for port in ports]


def serial_send(ser, data):
    """发送数据到串口"""
    if ser and ser.is_open:
        ser.write(data.encode('utf-8') + b'\r\n')


def serial_receive(ser):
    """接收串口数据"""
    while ser and ser.is_open:
        data = ser.readline().decode('utf-8').strip()
        if data:
            print(f"接收: {data}")


def __main__():
    # 列出可用串口
    while True:
        ports = list_serial_ports()
        print("可用串口:", ports)
        if not ports:
            print("没有找到可用串口")
            return
        port = input("请输入你要连接的串口名称或序号:")
        if port.isdigit() and 0 <= int(port) < len(ports):
            port = ports[int(port)]
            print(f"已选择 {port}")
        elif port.upper() not in ports:
            print("无效的串口名称或序号")
            return
        baudrate = input("请输入你要使用的波特率:")
        if not baudrate.isdigit():
            print("无效的波特率")
            return
        break
        # 打开选择的串口
    ser = serial.Serial(port, int(baudrate), timeout=1)
    print(f"已连接 {ports[0]}，波特率 {baudrate}")
    # 启动接收线程
    receive_thread = threading.Thread(target=serial_receive, args=(ser,))
    receive_thread.daemon = True
    receive_thread.start()

    # 主循环
    try:
        while True:
            data = input("输入要发送的数据(输入quit退出): ")
            if data.lower() == 'quit':
                break
            serial_send(ser, data)
    finally:
        ser.close()
        print("串口已关闭")


if __name__ == "__main__":
    __main__()
